package com.iob.coin.util;

import com.csvreader.CsvReader;
import com.iob.coin.util.logutil.Logger;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author: MengYuxin
 * @Date: 2021/3/10 21:06
 * 文件的上传功能
 */


@ConfigurationProperties(prefix = "fileutil")
@Component
@Data
public class FileUtil {

    private static Logger logger = new Logger(FileUtil.class.getSimpleName(),System.out);

    //存储从web端传来的文件
    public boolean saveFile(MultipartFile multipartFile,String savePath){
        try {
            File file=new File(savePath);
            multipartFile.transferTo(file);

            logger.log("saveFile","存储文件",new HashMap<String,String>(){{
                put("path",savePath);
            }});

        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public ArrayList<String[]> readFile(String filepath){
        try {
            ArrayList<String[]> csv=new ArrayList<String[]>();
            CsvReader reader = new CsvReader(filepath,',', StandardCharsets.UTF_8);
            reader.readHeaders();
            while (reader.readRecord()){
                String[] a=reader.getValues();
                csv.add(a);
            }
            reader.close();
            return csv;
        }catch (Exception e){
            System.out.println("error");
            e.printStackTrace();
        }
        return null;
    }

}
